package com.ruoyi.business.controller;

import cn.hutool.core.comparator.CompareUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.collect.Lists;
import com.ruoyi.business.domain.TRegisterDept;
import com.ruoyi.business.domain.TRegisterInfo;
import com.ruoyi.business.enums.*;
import com.ruoyi.business.service.ITRegisterDeptService;
import com.ruoyi.business.service.ITRegisterInfoService;
import com.ruoyi.business.vo.TRegisterDeptVo;
import com.ruoyi.business.vo.TRegisterInfoVo;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysUserRegisterDept;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysMenuService;
import com.ruoyi.system.service.ISysUserRegisterDeptService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 进修科室Controller
 *
 * @author Tellsea
 * @date 2024-01-17
 */
@Api(tags = "进修科室Controller")
@RestController
@RequestMapping("/business/registerDept")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class TRegisterDeptController extends BaseController {

    private final ITRegisterDeptService tRegisterDeptService;
    @Autowired
    private ISysUserRegisterDeptService sysUserRegisterDeptService;

    private final ITRegisterInfoService tRegisterInfoService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysMenuService menuService;

    @ApiOperation("查询进修科室列表")
    @PreAuthorize("@ss.hasPermi('business:registerDept:list')")
    @GetMapping("/list")
    public TableDataInfo<TRegisterDeptVo> list(TRegisterDeptVo entity) {
        return tRegisterDeptService.queryList(entity);
    }

    @ApiOperation("查询进修科室所有列表")
    @GetMapping("/listAll")
    public AjaxResult listAll(TRegisterDeptVo entity) {
//        entity.setUserId(SecurityUtils.getLoginUser().getUserId());
        return AjaxResult.success("查询成功", tRegisterDeptService.queryAll(entity));
    }

    @ApiOperation("导出进修科室列表")
    @PreAuthorize("@ss.hasPermi('business:registerDept:export')")
    @Log(title = "进修科室", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TRegisterDeptVo entity) {
        List<TRegisterDeptVo> list = tRegisterDeptService.queryAll(entity);
        ExcelUtil<TRegisterDeptVo> util = new ExcelUtil<>(TRegisterDeptVo.class);
        util.exportExcel(response, list, "进修科室数据");
    }

    @ApiOperation("判断是否能报名")
    @PostMapping(value = "/canRegister")
    public AjaxResult canRegister(@RequestBody TRegisterInfoVo tRegisterDeptVo) {
        boolean canRegister = true;
        // 查询该学员在当前科室的报名数据
        // 接口需要的参数 registerDeptId durationStartDate durationEndDate  batchName registerYear
        TRegisterInfoVo entity = new TRegisterInfoVo();
//        entity.setRegisterDeptId(tRegisterDeptVo.getRegisterDeptId());
        entity.setUserId(SecurityUtils.getLoginUser().getUserId());
        entity.setAgentUserId(SecurityUtils.getLoginUser().getUserId());
        TableDataInfo<TRegisterInfoVo> tRegisterInfoPage = tRegisterInfoService.queryIndexList(entity);
        List<TRegisterInfoVo> tRegisterInfoVos = tRegisterInfoPage.getRows();
        if(tRegisterInfoVos!=null && !tRegisterInfoVos.isEmpty()) {
            // 取消报到、已结业状态、已肆业状态，延期未确认、管理员已拒绝、科室审核（主任/秘书）拒绝
            // 删除以上终止的进修
            tRegisterInfoVos.removeIf(t->
                    Objects.equals(t.getNoticeStatus(), NoticeStatusEnums.CANCEL.getCode())
                            || Objects.equals(t.getNoticeStatus(), NoticeStatusEnums.DELAYED.getCode())
                            || Objects.equals(t.getSureStatus(), SureStatusEnums.DELAYED.getCode())
                            || Objects.equals(t.getGraduationStatus(), GraduationStatusEnums.NORMAL.getCode())
                            || Objects.equals(t.getGraduationStatus(), GraduationStatusEnums.BEFORE.getCode())
                            || Objects.equals(t.getGraduationStatus(), GraduationStatusEnums.EXTENSION.getCode())
                            || Objects.equals(t.getGraduationStatus(), GraduationStatusEnums.STOP.getCode())
                            || Objects.equals(t.getGraduationAuditStatus(), GraduationAuditStatusEnums.FAIL.getCode())
                            || Objects.equals(t.getPayStatus(), PayStatusEnums.REFUND.getCode())
                            || Objects.equals(t.getAuditStatus(), AuditStatusEnums.FAIL.getCode())
            );
            // 只判断正常的进修
            for (TRegisterInfoVo tRegisterInfoVo : tRegisterInfoVos) {
//                if(StringUtils.equals(tRegisterInfoVo.getRegisterYear(),tRegisterDeptVo.getRegisterYear())
//                        && !StringUtils.equals(tRegisterInfoVo.getBatchName(),tRegisterDeptVo.getBatchName())
//                        && tRegisterInfoVo.getDurationStartDate().compareTo(tRegisterDeptVo.getDurationStartDate())>=0
//                        && tRegisterInfoVo.getDurationEndDate().compareTo(tRegisterDeptVo.getDurationEndDate())<=0){
//                    return AjaxResult.error("您已经存在报名信息，同一时间段内只能报一个批次", false);
//                }
//                if(tRegisterInfoVo.getAuditStatus()==3
//                        && tRegisterInfoVo.getNoticeStatus()!=null
//                        && Objects.equals(tRegisterInfoVo.getRegisterDeptId(), tRegisterDeptVo.getRegisterDeptId())
//                        && tRegisterInfoVo.getNoticeStatus()==1){
//                    return AjaxResult.error("当前所选的进修科室，已经有了报名进修", false);
//                }
//                if(tRegisterInfoVo.getNoticeStatus()!=null
//                        && Objects.equals(tRegisterInfoVo.getRegisterDeptId(), tRegisterDeptVo.getRegisterDeptId())
//                        && tRegisterInfoVo.getNoticeStatus()==3){
//                    return AjaxResult.error("当前所选的进修科室，已确认报道不可再次报名", false);
//                }
//                if(StringUtils.equals(tRegisterInfoVo.getRegisterYear(),tRegisterDeptVo.getRegisterYear())
//                        && Objects.equals(tRegisterInfoVo.getUserId(), SecurityUtils.getUserId())
//                        && Objects.equals(tRegisterInfoVo.getRegisterDeptId(), tRegisterDeptVo.getRegisterDeptId())
//                        && StringUtils.equals(tRegisterInfoVo.getBatchName(),tRegisterDeptVo.getBatchName())
//                        && (!Objects.equals(tRegisterInfoVo.getAuditStatus(),AuditStatusEnums.SAVE.getCode())
//                        || !Objects.equals(tRegisterInfoVo.getAuditStatus(),AuditStatusEnums.RETURNED.getCode()))
//                ){
//                    return AjaxResult.error("您已经存在报名信息，同一科室同一批次只能报一次", false);
//                }
//                if(StringUtils.equals(tRegisterInfoVo.getRegisterYear(),tRegisterDeptVo.getRegisterYear())
//                        && Objects.equals(tRegisterInfoVo.getUserId(), SecurityUtils.getUserId())
////                        && StringUtils.equals(tRegisterInfoVo.getBatchName(),tRegisterDeptVo.getBatchName())
//                        && (Objects.equals(tRegisterInfoVo.getAuditStatus(),AuditStatusEnums.NO.getCode())
//                        || Objects.equals(tRegisterInfoVo.getAuditStatus(),AuditStatusEnums.WAIT.getCode()))
//                ){
//                    return AjaxResult.error("您有报名信息正在审核中，预计审核时间15个工作日，请在审核完成后，再确认是否报名！", false);
//                }
//                if(Objects.equals(tRegisterInfoVo.getUserId(), SecurityUtils.getUserId())
//                        && (Objects.equals(tRegisterInfoVo.getAuditStatus(),AuditStatusEnums.NO.getCode())
//                        || Objects.equals(tRegisterInfoVo.getAuditStatus(),AuditStatusEnums.WAIT.getCode())
//                        || Objects.equals(tRegisterInfoVo.getAuditStatus(),AuditStatusEnums.SUCCESS.getCode()))
//                        && ((tRegisterInfoVo.getDurationStartDate().compareTo(tRegisterDeptVo.getDurationStartDate()) >= 0 && tRegisterInfoVo.getDurationStartDate().compareTo(tRegisterDeptVo.getDurationEndDate()) <= 0)
//                          || (tRegisterInfoVo.getDurationEndDate().compareTo(tRegisterDeptVo.getDurationStartDate()) >= 0 && tRegisterInfoVo.getDurationEndDate().compareTo(tRegisterDeptVo.getDurationEndDate()) <= 0))
//                ){
//                    return AjaxResult.error("当前时间段已有报名，同一时间段无法多次报名", false);
//                }

                if(Objects.equals(tRegisterInfoVo.getUserId(), SecurityUtils.getUserId())
                        && ((tRegisterInfoVo.getDurationStartDate().compareTo(tRegisterDeptVo.getDurationStartDate()) >= 0 && tRegisterInfoVo.getDurationStartDate().compareTo(tRegisterDeptVo.getDurationEndDate()) <= 0)
                        || (tRegisterInfoVo.getDurationEndDate().compareTo(tRegisterDeptVo.getDurationStartDate()) >= 0 && tRegisterInfoVo.getDurationEndDate().compareTo(tRegisterDeptVo.getDurationEndDate()) <= 0))
                ){
                    return AjaxResult.error("当前时间段已有报名，同一时间段无法多次报名", false);
                }
            }
        }
        return AjaxResult.success("报名验证通过", canRegister);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        TRegisterInfoVo entity = new TRegisterInfoVo();
        entity.setUserId(SecurityUtils.getLoginUser().getUserId());
        entity.setAgentUserId(SecurityUtils.getLoginUser().getUserId());
        entity.setAuditStatus(AuditStatusEnums.SUCCESS.getCode());
        TableDataInfo<TRegisterInfoVo> tRegisterInfoPage = tRegisterInfoService.queryIndexListNoDetail(entity);
        List<TRegisterInfoVo> tRegisterInfoVos = tRegisterInfoPage.getRows();
        boolean removegqpx = tRegisterInfoVos == null || tRegisterInfoVos.isEmpty();
        if(removegqpx){
            // 查询当前登录账号是否有报名信息，当不存在报名信息时，去掉岗前培训
            menus.removeIf(next -> next.getMenuName().contains("岗前培训"));
        }

        TRegisterInfoVo endRegis = new TRegisterInfoVo();
        endRegis.setUserId(SecurityUtils.getLoginUser().getUserId());
//        endRegis.setAgentUserId(SecurityUtils.getLoginUser().getUserId());
        endRegis.setGraduationStatusList(Arrays.asList(0L,GraduationStatusEnums.NORMAL.getCode(),
                GraduationStatusEnums.BEFORE.getCode(),GraduationStatusEnums.EXTENSION.getCode()));
        TableDataInfo<TRegisterInfoVo> endRegisPage = tRegisterInfoService.queryIndexListNoDetail(endRegis);
        List<TRegisterInfoVo> endRegisList = endRegisPage.getRows();
        boolean removeEndReg = endRegisList == null || endRegisList.isEmpty();
        if(removeEndReg){
            // 查询当前登录账号除了终止进修的其他数据，如果没有就移除【我的进修】
            menus.removeIf(next -> next.getMenuName().contains("我的进修"));
        }

        return AjaxResult.success(menuService.buildMenus(menus));
    }

    @ApiOperation("判断进修科室是否能报名")
    @PreAuthorize("@ss.hasPermi('business:registerDept:query')")
    @GetMapping(value = "/getInfo/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success("查询成功", tRegisterDeptService.queryById(id));
    }

    @ApiOperation("新增进修科室")
    @PreAuthorize("@ss.hasPermi('business:registerDept:add')")
    @Log(title = "进修科室", businessType = BusinessType.INSERT)
    @PostMapping("add")
    public AjaxResult add(@RequestBody TRegisterDeptVo entity) {
        QueryWrapper<TRegisterDept> deptNameWrp = new QueryWrapper<>();
        deptNameWrp.eq("register_dept_name",entity.getRegisterDeptName());
        int deptCount = tRegisterDeptService.count(deptNameWrp);
        if(deptCount>0){
            return AjaxResult.error("当前进修科室名称已存在，请重新添加");
        }
        QueryWrapper<TRegisterDept> deptNumWrp = new QueryWrapper<>();
        deptNumWrp.eq("register_dept_number",entity.getRegisterDeptNumber());
        int numCount = tRegisterDeptService.count(deptNumWrp);
        if(numCount>0){
            String maxDeptNumber = tRegisterDeptService.getMaxDeptNumber();
            return AjaxResult.error("当前进修科室科目编号已存在，系统中最后一个科目编号是"+maxDeptNumber+"，请重新添加");
        }
        boolean save = tRegisterDeptService.save(entity);
        if(save){
//            SysUser sysUser = new SysUser();
//            sysUser.setRoleId(2L);
//            List<SysUser> sysUsers = userService.selectAllocatedList(sysUser);
            // 将改单位关联到管理员角色下的所有人
            List<TRegisterDept> list = tRegisterDeptService.list(deptNumWrp);
            if(list!=null && !list.isEmpty()
//                    && sysUsers!=null && !sysUsers.isEmpty()
            ){
                TRegisterDept tRegisterDept = list.get(0);
                Long registerDeptId = tRegisterDept.getId();
//                List<SysUserRegisterDept> userRegisterDeptList = Lists.newArrayList();
//                for (SysUser user : sysUsers) {
//                    SysUserRegisterDept sysUserRegisterDept = new SysUserRegisterDept();
//                    sysUserRegisterDept.setUserId(user.getUserId());
//                    sysUserRegisterDept.setRegisterDeptId(registerDeptId);
//                    userRegisterDeptList.add(sysUserRegisterDept);
//                }
//                sysUserRegisterDeptService.batchSysUserRegisterDept(userRegisterDeptList);
                // 给超级管理员绑定
                SysUserRegisterDept sysUserRegisterDept = new SysUserRegisterDept();
                sysUserRegisterDept.setUserId(1L);
                sysUserRegisterDept.setRegisterDeptId(registerDeptId);
                sysUserRegisterDeptService.save(sysUserRegisterDept);
            }

        }
        return toAjax(save);
    }

    @ApiOperation("获取最大进修科室编号")
    @PreAuthorize("@ss.hasPermi('business:registerDept:query')")
    @GetMapping(value = "/getMaxDeptNumber")
    public AjaxResult getMaxDeptNumber() {
        return AjaxResult.success("查询成功", tRegisterDeptService.getMaxDeptNumber());
    }

    @ApiOperation("修改进修科室")
    @PreAuthorize("@ss.hasPermi('business:registerDept:edit')")
    @Log(title = "进修科室", businessType = BusinessType.UPDATE)
    @PostMapping("edit")
    public AjaxResult edit(@RequestBody TRegisterDeptVo entity) {
        QueryWrapper<TRegisterDept> deptNameWrp = new QueryWrapper<>();
        deptNameWrp.eq("register_dept_name",entity.getRegisterDeptName());
        List<TRegisterDept> deptList = tRegisterDeptService.list(deptNameWrp);
        // 如果当前的修改的进修科室已存在 并且 已存在的主键id不是当前修改的主键id，那么就返回错误。
        if(deptList!=null && !deptList.isEmpty()){
            boolean hasSelf = false;
            for (TRegisterDept dept : deptList) {
                if (dept.getId().equals(entity.getId())) {
                    hasSelf = true;
                    break;
                }
            }
            if(!hasSelf){
                return AjaxResult.error("当前进修科室名称已存在，请重新添加");
            }
        }
        QueryWrapper<TRegisterDept> deptNumWrp = new QueryWrapper<>();
        deptNumWrp.eq("register_dept_number",entity.getRegisterDeptNumber());
        List<TRegisterDept> numList = tRegisterDeptService.list(deptNumWrp);
        // 如果当前的修改的进修科室编号已存在 并且 已存在的主键id不是当前修改的主键id，那么就返回错误。
        if(numList!=null && !numList.isEmpty()){
            boolean hasSelf = false;
            for (TRegisterDept dept : numList) {
                if (dept.getId().equals(entity.getId())) {
                    hasSelf = true;
                    break;
                }
            }
            if(!hasSelf){
                String maxDeptNumber = tRegisterDeptService.getMaxDeptNumber();
                return AjaxResult.error("当前进修科室编号已存在，系统中最后一个科目编号是"+maxDeptNumber+"，请重新添加");
            }
        }
        return toAjax(tRegisterDeptService.updateById(entity));
    }

    @ApiOperation("删除进修科室")
    @PreAuthorize("@ss.hasPermi('business:registerDept:remove')")
    @Log(title = "进修科室", businessType = BusinessType.DELETE)
	@GetMapping("/remove/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tRegisterDeptService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
